package com.horizon.cloud.stock.service.impl;

import com.horizon.cloud.seckill.dao.SeckillSegmentStockDao;
import com.horizon.cloud.seckill.dao.SeckillSkuDao;
import com.horizon.cloud.seckill.dao.po.SeckillSegmentStockPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Configuration
@Slf4j
@Service
public class SeckillSkuStockServiceImpl {
    @Resource
    SeckillSkuDao seckillSkuDao;

    @Resource
    SeckillSegmentStockDao seckillSegmentStockDao;

    //限速
    @Resource(name = "zkRateLimitServiceImpl")
    RateLimitService zkRateLimitServiceImpl;

    @Resource
    RedisRepository redisRepository;

    //初始化分段库存
    public void initSegmentStockAmount(Long skuId, int stockAmount, int segment) {
        int avRawStockCount = stockAmount / segment;
        for (int i = 0;i<segment;i++) {
            SeckillSegmentStockPO po = new SeckillSegmentStockPO();
            po.setSkuId(skuId);
            po.setSegmentIndex(i);
            po.setRawStockCount(avRawStockCount);
            //最后一个
            if(i==segment-1){
                po.setRawStockCount(avRawStockCount + stockAmount - avRawStockCount * segment);
            }
            po.setRawStockCount(po.getRawStockCount());
            seckillSegmentStockDao.save(po);
        }
    }
}
